<template>
  <a-tag
      v-for="(tag, index) of props.data"
      :key="tag"
      :style="{margin: '0 10px'}"
      closable
      @close="handleRemove(tag)"
  >
    {{ tag }}
  </a-tag>

  <a-input
      v-if="showInput"
      ref="inputRef"
      :style="{ width: '90px'}"
      size="mini"
      v-model.trim="inputVal"
      @keyup.enter="handleAdd"
      @blur="handleAdd"
  />
  <a-tag
      v-else
      :style="{
        width: '90px',
        backgroundColor: 'var(--color-fill-2)',
        border: '1px dashed var(--color-fill-3)',
        cursor: 'pointer',
      }"
      @click="handleEdit"
  >
    <template #icon>
      <icon-plus/>
    </template>
    添加
  </a-tag>
</template>

<script lang="ts" setup>
import {nextTick, ref} from "vue";
import {Message, Notification} from '@arco-design/web-vue';

const tags = ref([]);
const inputRef = ref(null);
const showInput = ref(false);
const inputVal = ref('');
const props = defineProps<{ data: string[] }>()
const emit = defineEmits<{ (e: 'add', tag: string): void, (e: 'remove', tag: string): void }>()
const handleEdit = () => {
  showInput.value = true;

  nextTick(() => {
    if (inputRef.value) {
      inputRef.value.focus();
    }
  });
};

const handleAdd = () => {
  console.log(inputVal.value)
  if (inputVal.value && !tags.value.includes(inputVal.value)) {
    tags.value.push(inputVal.value);
    emit('add', inputVal.value)
    inputVal.value = '';
  } else if (tags.value.includes(inputVal.value)) {
    Message.error('值不能重复')
  }
  showInput.value = false;
};

const handleRemove = (key) => {
  tags.value = tags.value.filter((tag) => tag !== key);
  emit('remove', key)
};
</script>